package com.infindo.frame.util;

import java.util.Hashtable;
import java.util.Random;
import java.util.Vector;

 

import android.content.Context;
 

  


public class StringUtil {

	/**
	 * 
	 * @return 01:20
	 */
	public static String format24HourMinute(int hour, int minute){
		String ret = "";
		ret = ret + StringUtil.twoDigitAppendFirstFormat(hour );
		ret = ret + ":";
		ret = ret + StringUtil.twoDigitAppendEndFormat(minute);
		return ret;
	}
	/**
	 * 
	 * @param no
	 * @return no 1 to 10
	 */
	public static String twoDigitAppendEndFormat(int no){
		String ret = no+"";
		if (ret.length()<2){
			ret = ret +"0";
		}
		return ret;
	}
	
	/**
	 * 
	 * @param no
	 * @return no 1 to 01
	 */
	public static String twoDigitAppendFirstFormat(int no){
		String ret = no+"";
		if (ret.length()<2){
			ret = "0"+ ret ;
		}
		return ret;
	}
	
	public static String replaceSpace(String str){
		if(str == null || str.length()==0)
			return "";
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<str.length();i++){
			char c = str.charAt(i);
			if(c == ' '){
				c = '_';
			}
			sb.append(c);
		}
		return sb.toString();
	}
	
	/**
	 * #a=10#b=20#am=100#
	 * @param sz    string
	 * @param unit  key
	 * @return value
	 */
	public static String propertyGet(final String sz, final String unit) {
		if (sz == null || unit == null || sz.length() == 0 || unit.length() == 0) {
			return null;
		}
		int signStart = -1, signEnd = 0;
		while (signStart < sz.length()) {
			signStart = sz.toLowerCase().indexOf(unit.toLowerCase(), signStart);
			if (signStart < 0) {
				return null;
			} else {
				if (sz.length() > signStart + unit.length()) {
					if (sz.charAt(signStart + unit.length()) == '=') {
						signStart = signStart + unit.length() + 1;
						signEnd = sz.indexOf("#", signStart);
						while(signEnd +1 < sz.length() && sz.charAt(signEnd +1) == '#' && signEnd+2 < sz.length()){
							signEnd = sz.indexOf("#", signEnd+2);
						}
						if (signStart <= signEnd) {
							String value = sz.substring(signStart, signEnd);
							if (value != null) {
								if (value.length() == 0) {
									return null;
								}
							}
 
							return value;
						}
					} else {
						signStart = sz.indexOf("#", signStart);
					}
				}
			}
		}
		return null;
	}
	
	public  static int[] BubbleSort(int[] sa)
    {
        int length = sa.length;
        int[] tempArray =null;
        tempArray =new int[length];
        System.arraycopy(sa, 0, tempArray, 0, length);
        for(int i=0;i<length;i++)
        {
            for(int j=length-1;j>0;j--)
            {
                if(tempArray[j]<tempArray[j-1])//compare one by one
                    swap(tempArray,j,j-1);
            }
        }
        return tempArray;
    }
	
	   public static int[] swap(int[] sa, int i, int j) 
	     { 
	        int tmp = sa[i]; 
	        sa[i] = sa[j]; 
	        sa[j] = tmp; 
	        return sa;
	     }
	   
	   public static int[] stringToInts(String data){
		   String[] strData = data.split(",");
		   int size = strData.length;
		   if(size<1)
			   return null;
		   int[] tempArray = new int[size-1];
		   for(int i=1;i<size;i++){
			       try{
			    	   tempArray[i-1]= Integer.parseInt(strData[i]);
		           }catch(NumberFormatException ne){
		        	   ne.getStackTrace();
		           }
		   }
		   tempArray = BubbleSort(tempArray);
		   return tempArray;
	   }
	   
	   public static String intsToString(int[] data){
		   StringBuffer sb = new StringBuffer(",");
		   for(int i=0;i<data.length;i++){
			   sb.append(data[i]+",");
		   }
		   return sb.toString();
	   }
	   
	public static String sortUserIds(String uids){
		return intsToString(stringToInts(uids));
	}
	
	public static int getUsersNum(String uids){
		int num = 0;
		String[] strData = uids.split(",");
		num = strData.length-1;
		if(num<0){
			return 0;
		}
		return num;
	}
	
	public static int getUserNumByNick(String nickname){
		int num = 0;
		String[] nicks = nickname.split(",");
		num = nicks.length;
		if(num<0){
			return 0;
		}
		return num;
	}
	
	@SuppressWarnings("unchecked")
	public static Vector sortStr(Vector  vec){
		int size = vec.size();
 
		String[] array = new String[size];
		for(int i=0;i<size;i++){
			array[i]= (String) vec.elementAt(i);
		}
		for(int i=0;i<size;i++)
	    {
	        for(int j=size-1;j>0;j--)
	        {
	                if(compareStr(array[j],array[j-1])){
	                    swap(array,j,j-1);
	                }
	        }
	    }
        Vector tempVec = new Vector();
		for(int i=0;i<size;i++){
			tempVec.addElement(array[i]);
		}
		return tempVec;
	}
	
	private static boolean compareStr(String s1,String s2){
		if(s1.equals(s2))
			return false;
		int size = s1.length();
		if(s1.length()>s2.length())
			size = s2.length();
		for(int i=0;i<size;i++){
			if(s1.charAt(i)<s2.charAt(i))
				return true;
			else if(s1.charAt(i)>s2.charAt(i))
				return false;
		}
		return false;
	}
	
    static Random rdm = new Random(System.currentTimeMillis());
	
	public static int getRandom(int size){
		return (rdm.nextInt() & 0x7FFFFFFF)%size;
	}
	
	private static void swap(String[] src, int i, int j) 
    { 
       String temp = src[i]; 
       src[i] = src[j]; 
       src[j] = temp; 
    }
	
	
//	  public static int mesureTextNum(String text,int offset,int dx,Font font)
//	  {
//	    int width=0;
//	    int num=0;
//	    for(int i=offset;i<text.length();i++)
//	    {
//	      width+=font.charWidth(text.charAt(i));
//	      if(width>dx)
//	      {
//	        break;
//	      }
//	      num++;
//	    }
//	    return num;
//	  }
//	  
//	  public static int mesureTextWidth(String text,Font font)
//	  {
//	    int width=0;
//	    if(text == null || text.length()==0)
//	    	return width;
//	    for(int i=0;i<text.length();i++)
//	    {
//	      width+=font.charWidth(text.charAt(i));
//	    }
//	    return width;
//	  }
	
	

	  
	/** 
	* 闁诲繐绻愬Λ妤呮偤瑜忕划顓㈡晜閼愁垼婀傞柡澶屽剱閸撴艾鐣烽弻銉ョ闁诡剙顢汣II闂佹椿鍣幏锟�	*  
	* @param cnStr 
	* @return String 
	*/  
	public static String getCnASCII(String cnStr)  
	{  
		StringBuffer strBuf = new StringBuffer();  
		// 闁诲繐绻愬Λ妤呮偤瑜忕划顓㈡晜閼愁垼婀傞柡澶屽剱閸撴艾鐣烽弻銉ョ闁归偊鍓涢幗鐔兼煠閸濆嫬锟界紒顭戝弮瀹曟岸鏁撻敓锟�		
		byte[] bGBK = cnStr.getBytes();  
		for (int i = 0; i < bGBK.length; i++)  
		{  
			strBuf.append(Integer.toHexString(bGBK[i] & 0xff));  
		}  
		return strBuf.toString();  
	}
	  
	//闂佽鎯屾禍婊嗐亹閸モ晜瀚氶柨鏂垮⒔閻骸菐閸ワ絽澧插ù纭锋嫹
	public static String getXmlString(String content){
		StringBuffer sb = new StringBuffer();
		int count = 0;
		int length = content.length();
		int start = -1;
		int end = -1;
 
		while(count<length){
			start = content.indexOf("<");
			end = content.indexOf(">");
			if(start!=-1&&end!=-1){
				sb.append(content.substring(0,start));
				content = content.substring(end+1);
				count+=end+1;
				continue;
			}else{
				if(content.length()==0)
					break;
				sb.append(content);
				count+=content.length();
			}
		}
		return  sb.toString();
	}
	

	public static String operTitle(String title){
		if(title!=null){
		   String[] tt = title.split("\n");
		   return tt[tt.length-1].toString();
		}
		return null;
	}
	
	public static String operString(String string){
        String str = null;
        if(string.length()>40){
        	str = string.substring(0, 40)+"...";
        }else{
        	str = string;
        }
        return str;
	}
	
	//缂傚倸鍊甸弲婵嬫偂閻犳潰ring
	public static String incString(String str){
		String st=null;
		if(str.length()>90){
			st = str.substring(0, 80)+"...";
		}else{
			st = str;
		}
		return st;
	}
	
	
	
	@SuppressWarnings("unchecked")
	public static Hashtable texts = new Hashtable();
	
	public static String getText(String name){
		if(texts != null){
			if(name != null){
				if(name.startsWith("::")){
					if (texts.get(name.substring(2)) != null) {
						return (String) texts.get(name.substring(2));
					} else {
						return "";
					}
				}else{
					return name;
				}
			}
		}
		return name;
	}
	@SuppressWarnings("unchecked")
	public static void init(Context context,String language){
		try{
			texts.clear();
			Vector fileContent = FileUtil.read_File_TextContent(context,"lang_"+language+".txt", "=");
			if(fileContent != null && fileContent.size() > 0){
				for(int i= 0;i< fileContent.size();i++){
					Vector lineContent = (Vector)fileContent.elementAt(i);
					texts.put(lineContent.elementAt(0), replaceWith((String)lineContent.elementAt(1),"==","="));
				}
			}
		}catch(Exception e){
		}
	}
	public static String replaceWith(String original,String find,String replace){
		if(original == null || original.length() == 0){
			return null;
		}
		StringBuffer sb = new StringBuffer();
		int istart = 0;
		while((istart = original.indexOf(find))>=0){
			sb.append(original.substring(0,istart)).append(replace);
			original = original.substring(istart+find.length());
		}
		if(original != null){
			sb.append(original);
		}
		return sb.toString();		
	}
	
    public static String splitString(String string){

		String ss = string.replaceAll("<"+"%"+">", "");
    	
    	return ss;
    }
	
    public static boolean isOk(String email){
    	boolean flag;
    		int emailnum = email.indexOf("@");
    		int potnum = email.indexOf(".");
    		if(emailnum !=-1 && emailnum >0 && potnum!= -1 && potnum>emailnum && potnum<email.length()-1){
    			flag = true;
    		}else{
    			flag = false;
    		}    		
		return flag;    	 
    }
    
    /*
	            	   sb.append("&amp;");
	                   break;
	               case '>' :
	            	   sb.append("&gt;");
	                   break;
	               case '<' :
	            	   sb.append("&lt;");
	                   break;
	               case '"' :
	            	   sb.append("&quot;");
	            	   break;
	               case '\'' :
	            	   sb.append("&apos;");
	                   break; 
     */
    
	public static String handleString(String str){
		StringBuffer sb  = new StringBuffer();
		int size = str.length();
		int index = 0;
		char[] tempChar = str.toCharArray();
		while(index<size){
             if(index+6<size){
			    if(tempChar[index]=='&'&&tempChar[index+1]=='#'
			    	&&Character.isDigit(tempChar[index+2])
			    	&&Character.isDigit(tempChar[index+3])
			    	&&Character.isDigit(tempChar[index+4])
			    	&&Character.isDigit(tempChar[index+5])
			    	&&tempChar[index+6]==';'){
				    	StringBuffer sb2 = new StringBuffer();
				    	sb2.append(tempChar[index+2]);
				    	sb2.append(tempChar[index+3]);
				    	sb2.append(tempChar[index+4]);
				    	sb2.append(tempChar[index+5]);
//				    	System.out.println("sb2:"+sb2.toString());
				    	sb.append((char)Integer.parseInt((sb2.toString())));
				    	
				    	index+=7;
				    	continue;
			    }else if(tempChar[index]=='&'&&tempChar[index+1]=='a'&&tempChar[index+2]=='m'&&tempChar[index+3]=='p'&&tempChar[index+4]==';'){
			    	 sb.append('&');
			    	 index+=5;
			    	 continue;
			    }else if(tempChar[index]=='&'&&tempChar[index+1]=='g'&&tempChar[index+2]=='t'&&tempChar[index+3]==';'){
			    	sb.append('>');
			    	index+=4;
			    	continue;
			    }else if(tempChar[index]=='&'&&tempChar[index+1]=='l'&&tempChar[index+2]=='t'&&tempChar[index+3]==';'){
			    	sb.append('<');
			    	index+=4;
			    	continue;
			    }else if(tempChar[index]=='&'&&tempChar[index+1]=='q'&&tempChar[index+2]=='u'&&tempChar[index+3]=='o'&&tempChar[index+4]=='t'&&tempChar[index+5]==';'){
			    	sb.append('"');
			    	index+=6;
			    	continue;
			    }else if(tempChar[index]=='&'&&tempChar[index+1]=='a'&&tempChar[index+2]=='p'&&tempChar[index+3]=='o'&&tempChar[index+4]=='s'&&tempChar[index+5]==';'){
			    	sb.append('\'');
			        index+=6;
			        continue;
			    }else if(tempChar[index]=='&'&&tempChar[index+1]=='n'&&tempChar[index+2]=='b'&&tempChar[index+3]=='s'&&tempChar[index+4]=='p'&&tempChar[index+5]==';'){
			    	sb.append('\n');
			    	index+=6;
			    	continue;
			    }
			    else{
			    	sb.append(tempChar[index]);
			    }
			}else{
				sb.append(tempChar[index]);
			}
			index++;
		}
		return sb.toString();
		
	}
	
 
	
	  public static String checkXml(String s)
	  {
		   StringBuffer sb = new StringBuffer();
	       for (int i = 0; i < s.length(); i++) 
	       {
	           char c = s.charAt(i);
	           switch (c) {
	              case '\n':
	           	  case '\r':
	              case '\t':
	              	 // We got a proguard optimization error, very strange, don't know why, currently just comment this line to pass.
	           		   //sb.append("");
	           		   sb.append("&#"+((int) c)+';');
	           		   break;
	               case '&' :
	            	   sb.append("&amp;");
	                   break;
	               case '>' :
	            	   sb.append("&gt;");
	                   break;
	               case '<' :
	            	   sb.append("&lt;");
	                   break;
	               case '"' :
	            	   sb.append("&quot;");
	            	   break;
	               case '\'' :
	            	   sb.append("&apos;");
	                   break;
	               default :
	            	   sb.append(c);
	             }   
	       }
	       return sb.toString();
     }
	 

	 
	public static String updateReadBlogUrl(String readUrl){
		if(readUrl.contains("/zh/")){
			readUrl = readUrl.replace("/zh/", "/");
		}else if(readUrl.contains("/my/")){
			readUrl = readUrl.replace("/my/", "/");
		}else if(readUrl.contains("/ta/")){
			readUrl = readUrl.replace("/ta/", "/");
		}
		
		return readUrl;		
	} 
	
	   public static  String checkUrl(String sign){
	    	  int size = sign.length();
	    	  int index = 0;
	    	  char[] tempChar = sign.toCharArray();
	    	  StringBuffer sb = new StringBuffer();
	    	  while(index<size){
	    		  if(tempChar[index]=='!'){
	    			  sb.append("%21");
	    		  }else if(tempChar[index]=='*'){
	    			  sb.append("%2A");
	    		  }else if(tempChar[index]=='\''){
	    			  sb.append("%27");
	    		  }else
	    		  if(tempChar[index]=='('){
	    			  sb.append("%28");
	    		  }else
	    		  if(tempChar[index]==')'){
	    			  sb.append("%29");
	    		  }else
	    		  if(tempChar[index]==';'){
	    			  sb.append("%3B");
	    		  }else
	    		  if(tempChar[index]==':'){
	    			  sb.append("%3A");
	    		  }else
	    		  if(tempChar[index]=='&'){
	    			  sb.append("%26");
	    		  }else
	    		  if(tempChar[index]=='='){
	    			  sb.append("%3D");
	    		  }else
	    		  if(tempChar[index]=='+'){
	    			  sb.append("%2B");
	    		  }else
	    		  if(tempChar[index]=='$'){
	    			  sb.append("%24");
	    		  }else
	    		  if(tempChar[index]==','){
	    			  sb.append("%2c");
	    		  }else
	    		  if(tempChar[index]=='/'){
	    			  sb.append("%2F");
	    		  }else
	    		  if(tempChar[index]=='?'){
	    			  sb.append("%3F");
	    		  }else
	    		  if(tempChar[index]=='#'){
	    			  sb.append("%23");
	    		  }else
	    		  if(tempChar[index]=='@'){
	    			  sb.append("%40");
	    		  }else
	    		  if(tempChar[index]=='['){
	    			  sb.append("%5B");
	    		  }else
	    		  if(tempChar[index]==']'){
	    			  sb.append("%5D");
	    		  }else
	    		  if(tempChar[index]==' '){
	    			  sb.append("+");
	    		  }else{
	    		     sb.append(tempChar[index]);
	    		  }
	    		  index++;
	    	  }
	    	  return sb.toString();
	    }
	   public static  String checkContent(String sign){
	    	  int size = sign.length();
	    	  int index = 0;
	    	  char[] tempChar = sign.toCharArray();
	    	  StringBuffer sb = new StringBuffer();
	    	  while(index<size){
	    		  if(tempChar[index]=='!'){
	    			  sb.append("%21");
	    		  }else if(tempChar[index]=='*'){
	    			  sb.append("%2A");
	    		  }else if(tempChar[index]=='\''){
	    			  sb.append("%27");
	    		  }else
	    		  if(tempChar[index]=='('){
	    			  sb.append("%28");
	    		  }else
	    		  if(tempChar[index]==')'){
	    			  sb.append("%29");
	    		  }else
	    		  if(tempChar[index]==';'){
	    			  sb.append("%3B");
	    		  }else
	    		  if(tempChar[index]==':'){
	    			  sb.append("%3A");
	    		  }else
	    		  if(tempChar[index]=='&'){
	    			  sb.append("%26");
	    		  }else
	    		  if(tempChar[index]=='='){
	    			  sb.append("%3D");
	    		  }else
	    		  if(tempChar[index]=='+'){
	    			  sb.append("%2B");
	    		  }else
	    		  if(tempChar[index]=='$'){
	    			  sb.append("%24");
	    		  }else
	    		  if(tempChar[index]==','){
	    			  sb.append("%2c");
	    		  }else
	    		  if(tempChar[index]=='/'){
	    			  sb.append("%2F");
	    		  }else
	    		  if(tempChar[index]=='?'){
	    			  sb.append("%3F");
	    		  }else
	    		  if(tempChar[index]=='#'){
	    			  sb.append("%23");
	    		  }else
	    		  if(tempChar[index]=='@'){
	    			  sb.append("%40");
	    		  }else
	    		  if(tempChar[index]=='['){
	    			  sb.append("%5B");
	    		  }else
	    		  if(tempChar[index]==']'){
	    			  sb.append("%5D");
	    		  }else
	    		  if(tempChar[index]==' '){
	    			  sb.append("%20");
	    		  }else{
	    		     sb.append(tempChar[index]);
	    		  }
	    		  index++;
	    	  }
	    	  return sb.toString();
	    }
}
